<template>
  <div class="chart-container">
    <slot></slot>
    <div ref="chartRef" class="chart-content"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import axios from 'axios';
import * as echarts from 'echarts/core';
import { PieChart } from 'echarts/charts';
import { TooltipComponent, LegendComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { GraphicComponent } from 'echarts/components'; // 导入 GraphicComponent

// 注册 GraphicComponent
echarts.use([TooltipComponent, LegendComponent, PieChart, GraphicComponent, CanvasRenderer]);

const chartRef = ref(null);
let chartInstance = null;

const option = ref({ // 用户评论数量 - Pie Chart Option
  tooltip: {
    trigger: 'item', formatter: '{b} : {c} ({d}%)',
    backgroundColor: 'rgba(0, 10, 30, 0.8)', borderColor: '#0ff', textStyle: { color: '#fff' }
  },
  legend: {
    right: '5%',
    textStyle: { color: 'rgba(204, 238, 255, 0.8)', fontSize: 10 },
    itemWidth: 10, itemHeight: 10, icon: 'circle'
  },
  // 新增 graphic 组件用于显示中心文本
  graphic: {
    elements: [
      {
        type: 'text',
        left: 'center', // 水平居中
        top: 'center', // 垂直居中，可能需要微调
        style: {
          text: '', // 初始文本为空
          fill: '#fff', // 文本颜色
          fontSize: 16, // 字体大小
          fontWeight: 'bold',
          textAlign: 'center',
          textVerticalAlign: 'middle'
        },
        // z: 100 // 确保文本在最上层（如果需要）
      }
    ]
  },
  series: [{
    name: '点赞数量', type: 'pie', radius: ['45%', '65%'], center: ['40%', '55%'], avoidLabelOverlap: true,
    label: { show: false, position: 'outside' },
    labelLine: { show: false },
    itemStyle: { borderRadius: 5, borderColor: 'rgba(10, 23, 62, 1)', borderWidth: 2 },
    emphasis: {
        label: { show: true, fontSize: '12', fontWeight: 'bold', color: '#fff' },
        itemStyle: { shadowBlur: 15, shadowOffsetX: 0, shadowColor: 'rgba(0, 198, 255, 0.5)' }
    },
    data: [],
    color: ['#00FFFF', '#00E5EE', '#40E0D0', '#7FFFD4', '#AFEEEE', '#B0E0E6', '#ADD8E6']
  }]
});

const initChart = async () => {
  if (!chartRef.value) return;
  // 销毁旧实例（如果存在），防止重复渲染和事件监听
  if (chartInstance) {
    chartInstance.dispose();
  }
  chartInstance = echarts.init(chartRef.value);
  try {
    const response = await axios.get('/api/praise_ranking');
    if (response.data.code === 200) {
        // 更新数据前，先清空中心文本
        option.value.graphic.elements[0].style.text = '';
        option.value.series[0].data = response.data.data;
        chartInstance.setOption(option.value);

        // 添加事件监听
        chartInstance.on('highlight', (params) => {
          // 高亮时更新中心文本为数据项名称
          chartInstance.setOption({
            graphic: {
              elements: [
                {
                  style: {
                    text: params.data.name // 获取高亮项的名称
                  }
                }
              ]
            }
          });
        });

        chartInstance.on('downplay', () => {
          // 取消高亮时清空中心文本
          chartInstance.setOption({
            graphic: {
              elements: [
                {
                  style: {
                    text: '' // 清空文本
                  }
                }
              ]
            }
          });
        });

    } else {
         console.error("Chart2 Error:", response.data.msg);
    }
  } catch (error) {
    console.error("Chart2 Network Error:", error);
  }
};

const resizeHandler = () => {
  chartInstance?.resize();
};

onMounted(async () => {
  await nextTick();
  initChart();
  window.addEventListener('resize', resizeHandler);
});

onUnmounted(() => {
  window.removeEventListener('resize', resizeHandler);
  chartInstance?.dispose();
});
</script>

<style scoped>
.chart-container { width: 100%; height: 100%; display: flex; flex-direction: column; }
.chart-content { flex-grow: 1; width: 100%; height: 100%; }
</style>